package com.qf.web.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.pojo.Profile;
import com.qf.service.ProfileService;
import com.qf.service.UserService;
import com.qf.service.impl.ProfileServiceImpl;
import com.qf.utils.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@WebServlet("/profileservlet")
@MultipartConfig(maxRequestSize = 1024*1024*20,maxFileSize = 1024*1024*20)
public class ProfileServlet extends BaseServlet{
    ApplicationContext app=new ClassPathXmlApplicationContext("/spring-context.xml");
    ProfileService profileService = (ProfileService) app.getBean("profileService");

    public String listProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNum = request.getParameter("pageNum");
        int page_num = 1;
        int page_size = 8;
        if (!StringUtils.isEmpty(pageNum)) {
            page_num = Integer.parseInt(pageNum);
            if (page_num < 1) {
                page_num = 1;
            }
        }
        PageHelper.startPage(page_num, page_size);
        try {
            ProfileService profileService = new ProfileServiceImpl();
            List<Profile> profileList = profileService.findByPage();

            PageInfo<Profile> pageInfo=new PageInfo<>(profileList);
            request.setAttribute("pageCount",pageInfo.getPages());
            request.getSession().setAttribute("pageNum",pageInfo.getPageNum());
            request.setAttribute("profileList", profileList);
            return "/list.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", e);
            return "/error.jsp";
        }

    }

    public String loadUpdateInfoProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)){
            request.setAttribute("error","id不能为空");
            return "/error.jsp";
        }

        try {
            Profile updateInfo=profileService.findById(Integer.parseInt(id));
            request.setAttribute("updateInfo",updateInfo);
            return "/update.jsp";
        } catch (Exception e) {
            request.setAttribute("error",e);
            return "/error.jsp";
        }
    }

    public String updateProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String birthday = request.getParameter("birthday");
        String gender = request.getParameter("gender");
        String career = request.getParameter("career");
        String address = request.getParameter("address");
        String mobile = request.getParameter("mobile");


        if (StringUtils.isEmpty(name)){
            request.setAttribute("error","姓名不能为空");
            return "/error.jsp";
        }
        if (StringUtils.isEmpty(birthday)){
            request.setAttribute("error","生日不能为空");
            return "/error.jsp";
        }
        if (StringUtils.isEmpty(gender)){
            request.setAttribute("error","性别不能为空");
            return "/error.jsp";
        }
        if (StringUtils.isEmpty(career)){
            request.setAttribute("error","职业不能为空");
            return "/error.jsp";
        }
        if (StringUtils.isEmpty(address)){
            request.setAttribute("error","地址不能为空");
            return "/error.jsp";
        }
        if (StringUtils.isEmpty(mobile)){
            request.setAttribute("error","电话不能为空");
            return "/error.jsp";
        }
        Part picture = request.getPart("picture");


        Profile profile=null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);
        filename = filename.substring(filename.lastIndexOf("\\") + 1);
        try {
            if ("".equals(filename)){
                profile=new Profile(Integer.parseInt(id),name,sdf.parse(birthday),gender,career,address,mobile,null);
                profileService.modify(profile);
            }else{
                String basePath = request.getServletContext().getRealPath("WEB-INF" + File.separator +"images");
                File file=new File(basePath);
                if (!file.exists()){
                    file.mkdirs();
                }


                picture.write(basePath+File.separator+filename);
                picture.delete();
                profile=new Profile(Integer.parseInt(id),name,sdf.parse(birthday),gender,career,address,mobile,filename);
                profileService.modify(profile);
            }
            return "/profileservlet?method=listProfile";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error",e);
            return "/error.jsp";
        }




    }

    public String imgProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        String id = request.getParameter("id");
        Profile profile = profileService.findById(Integer.parseInt(id));

        String realPath = request.getServletContext().getRealPath("WEB-INF" + File.separator +"images");
        String file=realPath+File.separator+profile.getPicture();

        FileInputStream fis=new FileInputStream(file);

        byte[] b=new byte[1024*8];
        int len;
        while((len=fis.read(b))!=-1){
            response.getOutputStream().write(b,0,len);
        }
        return null;
    }

    public String detailProfile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if (StringUtils.isEmpty(id)){
            request.setAttribute("error","id不能为空");
            return "/error.jsp";
        }

        try {
            Profile profile=profileService.findById(Integer.parseInt(id));
            request.setAttribute("profile",profile);
            return "/detail.jsp";
        } catch (NumberFormatException e) {
            request.setAttribute("error",e);
            return "/error.jsp";
        }


    }

}
